#include "XmlHandler.h"

#include "XmlIssuerMessageHandler.h"
#include "XmlRequestMessageHandler.h"
#include "XmlResponseMessageHandler.h"
XmlHandler::XmlHandler(void)
{
}

XmlHandler::~XmlHandler(void)
{
}
XmlHandler::XmlHandler(char* xmlString) {
	xmlDoc = new TiXmlDocument();
	xmlDoc->Parse(xmlString);
	if (xmlDoc->Error())
	{
		printf( "Error in %s: %s\n", xmlDoc->Value(), xmlDoc->ErrorDesc() );
		return;
	}
	rootNode = xmlDoc->FirstChildElement("Message");
	rootNode->Attribute("type", &type);
	rootNode->Attribute("id", &id);
	rootNode->Attribute("senderId", &sender);
	rootNode->Attribute("receiverId", &receiver);
}

char* XmlHandler::toXmlString() {
	xmlDoc = new TiXmlDocument();
	TiXmlDeclaration * decl = new TiXmlDeclaration("1.0", "UTF-8", "");
	rootNode = new TiXmlElement("Message");

	xmlDoc->LinkEndChild(decl);
	xmlDoc->LinkEndChild(rootNode);

	//add attributes for node Message
	addAttributeType();
	rootNode->SetAttribute("type", type);
	rootNode->SetAttribute("id", id);
	rootNode->SetAttribute("senderId", sender);
	rootNode->SetAttribute("receiverId", receiver);

	//add body for node Message
	addBody();
	xmlDoc->SaveFile("C:\\testXml.xml");
	TiXmlPrinter printer;
	xmlDoc->Accept( &printer ); 
	char* message = (char*) printer.CStr();
	char temp[MAX_XML_LENGTH];
	strcpy_s(temp, MAX_XML_LENGTH, message);
	for (int i = 0; i < sizeof(temp); i++) {
		if (temp[i] == '\n' || temp[i] == '\r') {
			temp[i] = ' ';

		}
	
	}
	return temp;
}
XmlHandler* XmlHandler::getMessageHandler(char* xmlString) {
	if (xmlString == NULL) {
		return NULL;
	}
	TiXmlDocument* rootNode = new TiXmlDocument();
	rootNode->Parse(xmlString);
	if (rootNode->Error())
	{
		printf( "Error in %s: %s\n", rootNode->Value(), rootNode->ErrorDesc() );
		return NULL;
	}
	TiXmlElement* messageNode = rootNode->FirstChildElement("Message");
	if (messageNode == NULL) {
		return NULL;
	}
	int type = -1;
	messageNode->Attribute("type", &type);
	switch (type)
    {
		case Constant::EncryptedMessage:
			return NULL;
		case Constant::AddMessage:
			return NULL;
		case Constant::EditMessage:
			return NULL;
		case Constant::DeleteMessage:
			return NULL;
		case Constant::ResponseMessage:
			return new XmlResponseMessageHandler(xmlString);
		case Constant::RequestMessage:
			return new XmlRequestMessageHandler(xmlString);
		case Constant::IssuerMessage:
			return new XmlIssuerMessageHandler(xmlString);
	                
    }
	return NULL;
};